//
//  SLHomeViewController.swift
//  langligelang
//
//  Created by 秦－政 on 2016/10/22.
//  Copyright © 2016年 pete. All rights reserved.
//

import UIKit
// cell 可重用表示符
private let statusCellIdentifier = "statusCellIdentifier"
class SLHomeViewController: SLVisitorViewController {
    // viewModel 对象
    let statusListViewModel = SLStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 判断是否登陆
        if !isLogin {
            // 设置访客视图信息
            visitorView?.setupVisitorViewInfo(imgName: nil, tilte: nil)
            return
        }
        setupUI()
        // 请求数据
        getStatusData()
    }
    // 监听事件
    @objc private func leftClick(){
        print("左边")
    }
    @objc private func rightClick(){
        print("右边")
        let vc = SLTempViewController()
        
        navigationController?.pushViewController(vc, animated: true)
    }
    private func setupUI(){
        // MARK: -
        setupNav()
        setupTableViewInfo()
        // 添加tipLabel
        if let nav = self.navigationController{
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
            // nav.navigationBar.frame.maxY  是导航栏的最大Y轴
            tipLabel.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.frame.width, height: 35)
        }
    }
    
    // MARK: - 设置 tableView 相关信息
    private func setupTableViewInfo(){
        
        // 设置数据源
        tableView.dataSource = self
        tableView.delegate = self
        // 注册 cell
        tableView.register(SLStatusCell.self, forCellReuseIdentifier: statusCellIdentifier)
        // cell 高度
        //        tableView.rowHeight = 300
        // 设置自适应行高
        tableView.rowHeight = UITableViewAutomaticDimension
        // 预估行高
        tableView.estimatedRowHeight = 150
        // tableView 显示个样式
        tableView.separatorStyle = .none
        // 设置footView
        tableView.tableFooterView = bottomView
        //        bottomView.startAnimating()
        // 添加下拉刷新控件
        tableView.addSubview(refreshControl)
        // 自定义下拉刷新控件
        refreshControl.addTarget(self, action: #selector(getStatusData), for: UIControlEvents.valueChanged)
        
    }
    // 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(setHighlightedImgName: "navigationbar_pop", title: nil, target: self, action: #selector(leftClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(setHighlightedImgName: "navigationbar_friendsearch", title: nil, target: self, action: #selector(rightClick))
    }
    // MARK: - tipLabel 动画
    fileprivate func startTipAnimation(message: String){
        if tipLabel.isHidden == false {
            // 表示正在执行动画
            return
        }
        tipLabel.isHidden = false
        tipLabel.text = message
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.frame.height)
        }) { (_) in
            
            UIView.animate(withDuration: 1, animations: {
                self.tipLabel.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    self.tipLabel.isHidden = true
            })
        }}
    // MARK: - 懒加载控件
    // 风火轮
    fileprivate lazy var bottomView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        // 设置颜色
        view.color = UIColor.purple
        return view
    }()
    // 系统的下拉刷新控件
    //    fileprivate lazy var refreshControl: UIRefreshControl = UIRefreshControl()
    // 自定义下拉刷新控件
    fileprivate lazy var refreshControl: SLRefreshControl = SLRefreshControl()
    // 添加tipLabel
    fileprivate lazy var tipLabel: UILabel = {
        let label = UILabel(textColor: UIColor.white, fontSize: 11, text: "没有加载到最新数据")
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        label.isHidden = true // 默认隐藏
        return label
    }()
}

// 请求数据
extension SLHomeViewController{
    // 请求数据
    func getStatusData(){
        // 委托 statusListViewModel 请求数据
        statusListViewModel.getHomeData(isPullUp: bottomView.isAnimating) { (isSuccess, message) in
            // 不是上拉加载执行tip动画
            if !self.bottomView.isAnimating {
                // 开启tip动画
                self.startTipAnimation(message: message)
            }
            
            if !isSuccess {
                print("请求失败")
            }else{
                // 成功刷新UI
                self.tableView.reloadData()
            }
            self.endRefreshing()
        }
    }
    // 停止下拉和上啦动画
    func endRefreshing() {
        //         停止动画
        self.bottomView.stopAnimating()
        //         下拉刷新也要停止
        self.refreshControl.endRefreshing()
    }
}

// 数据源
extension SLHomeViewController:UITableViewDataSource,UITableViewDelegate{
    @available(iOS 2.0, *)
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return statusListViewModel.dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: statusCellIdentifier, for: indexPath) as! SLStatusCell
        // cell属性赋值
        cell.statusViewModel = statusListViewModel.dataArray[indexPath.row]
        //        print(cell.statusViewModel)
        cell.selectionStyle = .none
        return cell
    }
    // 将要显示的Cell
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == statusListViewModel.dataArray.count - 1 && !bottomView.isAnimating{
            // 开启动画
            bottomView.startAnimating()
            // 马上加载数据
            getStatusData()
            
        }
    }
    
}
